package com.tsdykj.peng.diary.function;

import android.app.Activity;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Environment;
import android.util.Log;

import com.tsdykj.peng.diary.R;
import com.tsdykj.peng.diary.bean.UpdateInfo;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * Created by peng on 2015/4/22.
 */
public class DownloadTask extends AsyncTask<UpdateInfo, Integer, File> {
    private ProgressDialog pd;
    private Activity activity;

    public DownloadTask(Activity activity) {

        this.activity = activity;;
        pd = new ProgressDialog(activity);
        pd.setMax(100);
        pd.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        pd.setMessage(activity.getString(R.string.downloading_updating));
    }

    @Override
    protected File doInBackground(UpdateInfo... params) {

        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            URL url = null;

            try {
                url = new URL(PathManager.Host + "/update/download");
                Log.d("GETFILEFROMSERVER", url.toString());
                HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                conn.setConnectTimeout(5000);
                conn.setRequestProperty("Accept-Encoding", "identity");

                int maxLen = conn.getContentLength();

                Log.d("MaxLen: ", maxLen + ""); // -1 ?
                InputStream is = conn.getInputStream();

                File file = new File(Environment.getExternalStorageDirectory(), "new.apk");
                FileOutputStream fos = new FileOutputStream(file);
                BufferedInputStream bis = new BufferedInputStream(is);
                byte[] buffer = new byte[1024];
                int len;
                int total = -1;
                while ((len = bis.read(buffer)) != -1) {
                    fos.write(buffer, 0, len);
                    total += len;
                    publishProgress((int) ((total / (float) maxLen) * 100));
                }
                fos.close();
                bis.close();
                is.close();
                return file;

            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    @Override
    protected void onPreExecute() {
        pd.show();
    }

    @Override
    protected void onProgressUpdate(Integer... values) {
        pd.setProgress(values[0]);
    }

    @Override
    protected void onPostExecute(File file) {
        pd.dismiss();
        PUtils.InstallApk(activity, file);

    }
}
